<?php
/**
 * Created by PhpStorm.
 * User: kobe.wang
 * Date: 2019/3/18
 * Time: 15:24
 */
namespace App\Common;

use Illuminate\Support\Facades\Redis;

class SwooleSocket
{
    private static $websocket = null;

    private function __construct()
    {

    }

    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    protected static function init()
    {
        if (empty(self::$websocket)) {
            self::$websocket = new \swoole_websocket_server("0.0.0.0", 8802);
            //创建websocket服务器对象，监听0.0.0.0:9502端口
            //监听WebSocket连接打开事件
            self::$websocket->on('open', function ($ws, $request) {
                var_dump($request->fd, $request->get, $request->server);
                $ws->push($request->fd, "hello, welcome\n");
            });
            //监听WebSocket消息事件
            self::$websocket->on('message', function ($ws, $frame) {
                echo "Message: {$frame->data}\n";
                $data = json_decode($frame->data,true);
                Redis::Hset($frame->fd,'username',$data['username']);

                $send_data = Redis::hget($frame->fd,'username');
                $ws->push($frame->fd, "server: {$send_data} hello!!!");
            });

            //监听WebSocket连接关闭事件
            self::$websocket->on('close', function ($ws, $fd) {
                echo "client-{$fd} is closed\n";
            });

            self::$websocket->on('request', function ($request, $response) {
                // 接收http请求从get获取message参数的值，给用户推送
                // $this->server->connections 遍历所有websocket连接用户的fd，给所有用户推送
                foreach ( self::$websocket->connections as $fd) {
                    self::$websocket->push($fd, $request->get['message']);
                }
            });

            self::$websocket->start();
        }

        return self::$websocket;
    }

    public static function getWebsocket()
    {
        $ret = self::init();
        if ($ret == false) {
            return false;
        }
        return $ret;
    }

    public static function start()
    {

    }

    public static function message()
    {

    }
    public static function pushMessage()
    {
        $websocket_ins = self::getWebsocket();
        // $server->connections 遍历所有websocket连接用户的fd，给所有用户推送
        foreach ($websocket_ins->connections as $fd) {
            $websocket_ins->push($fd,  "server: push message hello!!!");
        }
    }
}